<?php
namespace app\exam\controller;
error_reporting(E_ALL ^ E_NOTICE);

use think\Controller;
use app\exam\model\CandidateModel;
class Common extends Controller
{
    protected $args = array();//其他get，post参数
    protected $_method = '';

    public function _initialize(){
        $_POST = saddslashes($_POST);
        $_GET = saddslashes($_GET);
        $_REQUEST = saddslashes($_REQUEST);
        $this->_method = strtolower(request()->method());

        $this->args = saddslashes($this->_params());

        $args_log = json_encode($this->args,JSON_UNESCAPED_UNICODE);
        $len = strlen($args_log);
        DLOG("args=".$args_log.' req_len='.$len,'run','exam');
    }

    /*
     * 获取参数列表 get、post、put、delete
     *  @author JiaXu
     *  @date 2016-09-19
     */
    public function _params(){
        $parma_arr = array();
        if($this->_method == 'get' || $this->_method == 'delete'){
            unset($_GET['_URL_']);
            $parma_arr = $_GET;
        }elseif($this->_method=='post'){
            $parma_arr = $_POST;
        }else{
            $str = file_get_contents("php://input");
            $st_arr = explode("&", $str);
            for($i=0; $i<count($st_arr); $i++){
                $temp = explode("=", $st_arr[$i]);
                $parma_arr[$temp[0]] =$temp[1];
            }
        }
        return $parma_arr;
    }

    /*
    * 统一出口
    *  @author JiaXu
    *  @date 2016-09-19
    */
    function _response($params){
        header("Content-Type:application/json;charset=utf-8");
        if($params['code'] == 0){
            $params['code']='0';
            $params['msg'] = 'success';
        }else{
            if(isset($params['msg']) == false){
                $params['msg'] = error_code($params['code']);
            }
        }
        $json   =   json_encode($params,JSON_UNESCAPED_UNICODE);
        $len    =       strlen($json);
        DLOG($json.' resp_len='.$len,'run','exam');
        echo json_encode($params, JSON_UNESCAPED_UNICODE);
        exit();
    }

    /*
        校验token有效性
        params:
        return:
            boolean
    */
    public function _checkToken()
    {
        $CandidateModel = new CandidateModel();
        $token = trim($this->args['token']);
        $candidate = $CandidateModel->getCandidateInfoByToken($token);

        if($candidate === false){
            $res = array(
                'code' => '0004'
            );
            $this->_response($res);
        }
    }
}